package com.bloveoacom.weichi.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.bloveoacom.base.AppContext;
import com.bloveoacom.base.BaseList2Activity;
import com.bloveoacom.base.UserInfoBean;
import com.bloveoacom.exception.ApiException;
import com.bloveoacom.http.HttpMethods;
import com.bloveoacom.http.HttpResult;
import com.bloveoacom.http.MessageModel;
import com.bloveoacom.http.RxBus;
import com.bloveoacom.http.RxHelper;
import com.bloveoacom.observer.BaseSubscriber2;
import com.bloveoacom.pay.AlipayResult;
import com.bloveoacom.pay.PayParameter;
import com.bloveoacom.util.AESCipher;
import com.bloveoacom.util.ActivityUtil;
import com.bloveoacom.util.DialogUtil;
import com.bloveoacom.util.DisplayUtil;
import com.bloveoacom.util.GlideApp;
import com.bloveoacom.util.GlideUtil;
import com.bloveoacom.util.GsonUtil;
import com.bloveoacom.util.NumberUtil;
import com.bloveoacom.util.PicCameraLocalUtil;
import com.bloveoacom.util.ShareUtils;
import com.bloveoacom.util.StringUtils;
import com.bloveoacom.util.ToastUtil;
import com.bloveoacom.weichi.R;
import com.bloveoacom.weichi.bean.ActivityDetailBean;
import com.bloveoacom.weichi.bean.BuyBean;
import com.bloveoacom.weichi.bean.CreateEosWalletBean;
import com.bloveoacom.weichi.bean.SimpleBean;
import com.bloveoacom.weichi.bean.WXPayBean;
import com.bloveoacom.weichi.wxapi.WXPayEntryActivity;
import com.bloveoacom.weight.ActorInfoDialog;
import com.bloveoacom.weight.InputDialog;
import com.bloveoacom.weight.LlkjToolBar;
import com.bloveoacom.weight.PayDialog;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.reactivestreams.Publisher;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.bloveoacom.http.MessageModel.BUY_OK;
import static com.bloveoacom.http.MessageModel.TU_TYPE_UPDATEUSERINFO;
import static com.bloveoacom.util.AESCipher.KEY;
import static com.bloveoacom.util.Constant.INTENT_ACTIVITYID;
import static com.bloveoacom.util.GlideUtil.default_err;


public class ActivityDetailActivity extends BaseList2Activity<ActivityDetailBean.StarListBean> {
    @BindView(R.id.title_bar)
    LlkjToolBar mToolbar;
    @BindView(R.id.tv_buy)
    TextView tvBuy;
    @BindView(R.id.iv_share_pic)
    ImageView iv_share_pic;
    @BindView(R.id.layout_share)
    View layoutShare;
    ViewHolder viewHolder;
    private List<ActivityDetailBean.StarListBean> starList;
    private BottomSheetDialog bottomSheetBuyDialog;
    private PayDialog payDialog;
    private ActorInfoDialog actorInfoDialog;
    private InputDialog inputCountDialog, inputPasswordDialog;
    private String activityId;
    private ActivityDetailBean activityDetailBean;
    private int maxEumNum = 0;



    @Override
    public int getLayoutResId() {
        return R.layout.activity_activity_detail;
    }

    @Override
    public void initView() {
        super.initView();
        mToolbar.setToolBar("活动详情",
                true, "", R.drawable.ic_back, true, "", R.drawable.ic_share);
        tvBuy.setClickable(false);
    }

    @Override
    protected View getViewSetTB() {
        return mToolbar;
    }

    @Override
    public void getBundleExtras(Bundle extras) {
        activityId = extras.getString(INTENT_ACTIVITYID);
    }

    ActivityDetailBean.StarListBean starListBean;
    @Override
    public void initListener() {
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                starListBean = starList.get(position);
                switch (view.getId()) {
                    case R.id.iv_header_photo:
                        if (null != starListBean) {
                            showStarInfoDialog(starListBean);
                        }
                        break;
                    case R.id.tv_reward:
                        showInputCountDialog();
                        break;
                    default:
                        break;
                }
            }
        });
        mToolbar.setRightButtonOnClickLinster(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                share();
            }
        });
    }

    @Override
    protected int getItemLayout() {
        return R.layout.rv_item_activitydetail_actor;
    }

    @Override
    protected void convertView(BaseViewHolder helper, ActivityDetailBean.StarListBean item) {
        helper.setText(R.id.tv_name, item.getStatName());
        helper.setText(R.id.tv_emt_count, item.getEmtNum() + "EMT");
        helper.addOnClickListener(R.id.iv_header_photo);
        helper.addOnClickListener(R.id.tv_reward);
        ProgressBar emtNumProbar = helper.getView(R.id.progressBar);
        emtNumProbar.setProgress(item.getEmtNum());
        //emtNumProbar.setProgress(helper.getAdapterPosition());
        emtNumProbar.setMax(maxEumNum);
        //emtNumProbar.setMax(10);

        //活动结束了才有皇冠没有赞按钮
        if(activityDetailBean.getActivityStatus()==2){
            helper.setVisible(R.id.iv_winner,helper.getAdapterPosition()==1);
            helper.setVisible(R.id.tv_reward,false);
            if(helper.getAdapterPosition()==1){
                emtNumProbar.setProgressDrawable(ContextCompat.getDrawable(mContext,R.drawable.shape_progressbar2));
            }else{
                emtNumProbar.setProgressDrawable(ContextCompat.getDrawable(mContext,R.drawable.shape_progressbar));
            }
        }else{
            helper.setVisible(R.id.tv_reward,true);
            emtNumProbar.setProgressDrawable(ContextCompat.getDrawable(mContext,R.drawable.shape_progressbar));
        }
        GlideUtil.loadCircleImage(helper.getView(R.id.iv_header_photo), StringUtils.getFullUrl(item.getStarImg(), 0));


    }

    @Override
    protected void getData() {
        if (!TextUtils.isEmpty(activityId)) {
            BaseSubscriber2<ActivityDetailBean> baseSubscriber2 = HttpMethods.getInstance().getHttpService().getActivityDetail(activityId, UserInfoBean.getInstance().getToken()).compose(RxHelper.getData()).subscribeWith(new BaseSubscriber2<ActivityDetailBean>(this) {
                @Override
                public void onNext(ActivityDetailBean o) {
                    super.onNext(o);
                    activityDetailBean =  o;
                    if (null != activityDetailBean) {
                        setHeaderData();
                        setBuyBtn();
                        if (null != activityDetailBean.getStarList()) {
                            starList = activityDetailBean.getStarList();
                            maxEumNum = getMaxEmtNum();
                            doData(starList);
                        }
                    }
                }
            });
            addDispose(baseSubscriber2);
        }
    }


    private Bitmap shareBitmap;
    private File sharefile;
    private Dialog dialog;
    private void share() {
        if (dialog == null || sharefile == null) {
            shareBitmap = PicCameraLocalUtil.getBitmap(layoutShare);
            sharefile = PicCameraLocalUtil.saveBitmap(mContext,shareBitmap,"hd_detail");
            AppContext.mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    dialog = DialogUtil.getPicBottomDialog2(mContext, new DialogUtil.PhotoDoWhat() {
                        @Override
                        public void doone() {
                            ShareUtils.shareFriends(sharefile.getPath(), 0);
                            DialogUtil.dissDialog(dialog);
                            ToastUtil.makeShortText(mContext, "分享操作正在后台进行");
                        }

                        @Override
                        public void dotwo() {
                            ShareUtils.shareFriends(sharefile.getPath(), 1);
                            DialogUtil.dissDialog(dialog);
                            ToastUtil.makeShortText(mContext, "分享操作正在后台进行");
                        }
                        @Override
                        public void dothree() {
                            DialogUtil.dissDialog(dialog);
                        }
                    }, sharefile);
                    DialogUtil.showDialog(dialog);
                }
            }, 1000);

        } else {
            DialogUtil.showDialog(dialog);
        }
    }

    @OnClick(R.id.tv_buy)
    public void onViewClicked() {
        showBuyDialog();
    }

    private void setHeaderData() {
        GlideUtil.loadImageForBlur(viewHolder.ivBg, StringUtils.getFullUrl(activityDetailBean.getPosters(), 0));
        GlideApp.with(mContext).asBitmap().load(StringUtils.getFullUrl(activityDetailBean.getImg(), 0)).placeholder(default_err)
                .error(default_err)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(new SimpleTarget<Bitmap>(){
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                iv_share_pic.getLayoutParams().width = DisplayUtil.getDensityWdith(mContext);
                iv_share_pic.getLayoutParams().height = resource.getHeight()*iv_share_pic.getLayoutParams().width/resource.getWidth();
                iv_share_pic.setImageBitmap(resource);
            }
        });
        GlideUtil.loadRoundmage(viewHolder.ivPhoto, StringUtils.getFullUrl(activityDetailBean.getImg(), 0));
        //GlideUtil.loadImage(iv_share_pic, StringUtils.getFullUrl(activityDetailBean.getImg(), 0));
        viewHolder.tvTitle.setText(activityDetailBean.getTitle());
        viewHolder.tvArea.setText(activityDetailBean.getPlace());
        viewHolder.tvDate.setText(activityDetailBean.getActivityTime());
        viewHolder.tvPrice.setText(String.format("¥%s", activityDetailBean.getPrice()));
        viewHolder.tvDateStartAndEnd.setText(String.format("%s-%s", activityDetailBean.getStartTime(), activityDetailBean.getEndTime()));
        viewHolder.tvAddress.setText(activityDetailBean.getDetailedPlace());
    }

    private void setBuyBtn() {
        //售票中 和去购票
        if (activityDetailBean.getIsCanTicket()) {
            //未购票
            tvBuy.setText("去购票");
            tvBuy.setBackgroundResource(R.drawable.shape_buy_btn);
            tvBuy.setClickable(true);
        } else {
             if(activityDetailBean.isCanTicket==1){
                 tvBuy.setText("已购票");
             }else{
                 tvBuy.setText("去购票");
             }
            tvBuy.setBackgroundResource(R.drawable.shape_buy_btn_gray);
            tvBuy.setClickable(false);
        }
    }

    @Override
    public void addViewForAdapter() {
        super.addViewForAdapter();
        adapter.addHeaderView(getHeaderView());
    }

    private View getHeaderView() {
        View view = getLayoutInflater().inflate(R.layout.activity_activity_detail_header, (ViewGroup) mRecyclerView.getParent(), false);
        viewHolder = new ViewHolder(view);
        return view;
    }

    static class ViewHolder {
        @BindView(R.id.iv_bg)
        ImageView ivBg;
        @BindView(R.id.iv_photo)
        ImageView ivPhoto;
        @BindView(R.id.tv_title)
        TextView tvTitle;
        @BindView(R.id.tv_area)
        TextView tvArea;
        @BindView(R.id.tv_date)
        TextView tvDate;
        @BindView(R.id.tv_price)
        TextView tvPrice;
        @BindView(R.id.tv_date_start_and_end)
        TextView tvDateStartAndEnd;
        @BindView(R.id.tv_address)
        TextView tvAddress;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    private int getMaxEmtNum() {
        int maxEmtNum = 0;
        if (null != starList) {
            for (int i = 0; i < starList.size(); i++) {
                if (starList.get(i).getEmtNum() > maxEmtNum) {
                    maxEmtNum = starList.get(i).getEmtNum();
                }
            }
        }
        return maxEmtNum;
    }
    BuyBean buyBean;
    private void showBuyDialog() {
        if (null == bottomSheetBuyDialog && null != activityDetailBean) {
            bottomSheetBuyDialog = DialogUtil.getBottomBuyDialog(this, new DialogUtil.BuyDialogListener() {
                @Override
                public void buy(BuyBean buyBean1) {
                    buyBean = buyBean1;
                    showPayDialog();
                }
            }, activityDetailBean);
        }
        bottomSheetBuyDialog.show();
    }

    SimpleBean simpleBean;
    private void pay2(int payType){
        if(payType==1){
            HttpMethods.getInstance().getHttpService().buyTicket(UserInfoBean.getInstance().getToken(),activityId,buyBean.num,buyBean.price,"1").compose(RxHelper.getData()).subscribeWith(new BaseSubscriber2<Object>(this){
                @Override
                public void onNext(Object o) {
                    super.onNext(o);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            PayTask alipay = new PayTask(ActivityDetailActivity.this);
                            SimpleBean simpleBean = GsonUtil.GsonToBean(GsonUtil.GsonString(o), SimpleBean.class);
                            Map<String, String> resultMap = alipay.payV2(simpleBean.sign, true);
                            AlipayResult alipayResult = new AlipayResult(resultMap);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (alipayResult.isPaySuccess()) {
                                        activityDetailBean.isCanTicket = 1;
                                        setBuyBtn();
                                        ActivityUtil.startActivity(mContext,OrderDetailActivity.class,simpleBean.orderId);
                                        RxBus.getInstance().send(new MessageModel(BUY_OK));
                                    } else {
                                        if (!alipayResult.isPayCancel())
                                            ToastUtil.makeShortText(mContext, mContext.getString(R.string.payment_failure));

                                    }
                                }
                            });
                        }
                    }).start();
                }
            });
        }else{
            HttpMethods.getInstance().getHttpService().buyTicket(UserInfoBean.getInstance().getToken(),activityId,buyBean.num,buyBean.price,"0").compose(RxHelper.getData()).subscribeWith(new BaseSubscriber2<Object>(this){
                @Override
                public void onNext(Object o) {
                    super.onNext(o);
                    Intent intent = new Intent(mContext, WXPayEntryActivity.class);
                    startActivityForResult(intent, 100);
                    simpleBean = GsonUtil.GsonToBean(GsonUtil.GsonString(o), SimpleBean.class);
                    WXPayBean wxPayBean = GsonUtil.GsonToBean(simpleBean.sign, WXPayBean.class);
                    final IWXAPI msgApi = WXAPIFactory.createWXAPI(mContext, null);
                    msgApi.registerApp(PayParameter.WX_APP_ID);
                    PayReq request = new PayReq();
                    request.appId = wxPayBean.appid;
                    request.partnerId = wxPayBean.partnerid;
                    request.prepayId = wxPayBean.prepayid;
                    request.nonceStr = wxPayBean.noncestr;
                    request.timeStamp = wxPayBean.timestamp;
                    request.packageValue = wxPayBean.packageX;
                    request.sign = wxPayBean.sign;
                    boolean sendReq = msgApi.sendReq(request);
                    String result = "";
                    if (!sendReq) {
                        if (!msgApi.isWXAppInstalled()) {
                            result = getString(R.string.please_install_wechat);
                        } else if (!msgApi.isWXAppSupportAPI()) {
                            result = getString(R.string.wechat_client_inavailable);
                        } else {
                            result = getString(R.string.payment_failure);
                        }
                    }
                    if(!StringUtils.isEmpty(result)){
                        ToastUtil.makeShortText(mContext,result);
                    }
                }
            });

        }
    }

    private void showPayDialog() {
        if (payDialog == null) {
            payDialog = new PayDialog(this, R.style.MyDialogStyle);
            payDialog.setItemClickListener(new PayDialog.ItemClickListener() {
                @Override
                public void pay(int payType) {
                    pay2(payType);
                }
            });
        }
        payDialog.show();
    }

    private void showStarInfoDialog(ActivityDetailBean.StarListBean starListBean) {
        actorInfoDialog = new ActorInfoDialog(this, starListBean, R.style.MyDialogStyle);
        actorInfoDialog.show();
    }

    private void showInputCountDialog() {
        if (inputCountDialog == null) {
            inputCountDialog = new InputDialog(this, "输入数量", "输入打赏数量", false, true, R.style.MyDialogStyle);
            inputCountDialog.setItemClickListener(new InputDialog.ItemClickListener() {
                @Override
                public void left() {

                }

                @Override
                public void right(String content) {
                    rewardNum = NumberUtil.getIntByStr(content);
                    showInputPasswordDialog();
                }
            });
        }
        inputCountDialog.show();
    }



    private void reward(String pwd){
        DialogUtil.dissDialog(inputPasswordDialog);
        BaseSubscriber2<Object> objectBaseSubscriber2 =  HttpMethods.getInstance().getHttpService().findTimeStamp(UserInfoBean.getInstance().getToken()).subscribeOn(Schedulers.io()).flatMap(new Function<HttpResult<Object>, Publisher<HttpResult<Object>>>() {
            @Override
            public Publisher<HttpResult<Object>> apply(HttpResult<Object> objectHttpResult) throws Exception {
                if (objectHttpResult.isOk()) {
                    Object o = objectHttpResult.data;
                    SimpleBean simpleBean = GsonUtil.GsonToBean(GsonUtil.GsonString(o), SimpleBean.class);
                    String s = AESCipher.decryptAES(simpleBean.timeStamp);
                    CreateEosWalletBean transInfoBean = new CreateEosWalletBean(pwd, s);
                    String sign = AESCipher.encryptAES(GsonUtil.GsonString(transInfoBean), KEY);
                    return HttpMethods.getInstance().getHttpService().exceptional(UserInfoBean.getInstance().getToken(),activityId,starListBean.getStarId(),sign,rewardNum);
                } else {
                    return Flowable.error(new ApiException(objectHttpResult.code, objectHttpResult.msg));
                }
            }
        }).compose(RxHelper.getData()).subscribeWith(new BaseSubscriber2<Object>(ActivityDetailActivity.this){
            @Override
            public void onNext(Object o) {
                super.onNext(o);
                ToastUtil.makeShortText(mContext,"打赏成功");
                RxBus.getInstance().send(new MessageModel(TU_TYPE_UPDATEUSERINFO));
                getData();

            }
        });
        addDispose(objectBaseSubscriber2);
    }

    private int rewardNum,type;
    private void showInputPasswordDialog() {
        if (inputPasswordDialog == null) {
            inputPasswordDialog = new InputDialog(this, "输入密码", "Password", true, false, R.style.MyDialogStyle);
            inputPasswordDialog.setItemClickListener(new InputDialog.ItemClickListener() {
                @Override
                public void left() {

                }

                @Override
                public void right(String content) {
                    reward(content);
                }
            });
        }
        inputPasswordDialog.show();
    }

    @Override
    public boolean isLoadMore() {
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 100:
                switch (resultCode) {
                    case RESULT_OK:
                        activityDetailBean.isCanTicket = 1;
                        setBuyBtn();
                        ActivityUtil.startActivity(mContext,OrderDetailActivity.class,simpleBean.orderId);
                        RxBus.getInstance().send(new MessageModel(BUY_OK));
                        break;
                }
                break;
        }
    }
}
